package sample.ui

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.script.tes.appContext
import android.content.ClipboardManagerService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class RequireCaptureActivity: BaseActivity() {
    companion object {
        private var captureCallback: ((Int, Intent) -> Unit)? = null
        fun require(context: Context, callback: ((Int, Intent) -> Unit)?) {
            captureCallback = callback
            val intent = Intent(context, RequireCaptureActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    private var job: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setDimAmount(0f)
        window.decorView.setBackgroundColor(Color.TRANSPARENT)

        val manager =
            appContext.getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        val intent = manager.createScreenCaptureIntent()
        val startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            val data = it.data
            if (it.resultCode == RESULT_OK && data != null) {
                captureCallback?.invoke(it.resultCode, data)
                captureCallback = null
            }
            job?.cancel()
            finish()
        }
        startActivity.launch(intent)
        job = lifecycleScope.launch(Dispatchers.Main) {
            while (true) {
                delay(500)
                ClipboardManagerService.autoAcceptScreenCapturePermission()
                delay(2000)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        captureCallback = null
        job?.cancel()
    }
}